//#ifdef APP-PLUS
const quantum = uni.requireNativePlugin('Quantum')
// import { Base64 } from 'js-base64';
//#endif
/*
获取全局配置需要量子传输的接口
传入当前url 返回true配置了量子
*/
function qssList(url) {
	let quantumApis = []
	try {
		quantumApis = uni.getStorageSync('storage_key');
		//console.log('获取到配置量子接口', quantumApis);
	} catch (e) {
		// error
	}
	//当前url是不是配置量子
	let boole = quantumApis.includes(url)
	return boole
}
/*
国科量子解密 
需要传入解密的字符串和秘钥secretKey
*/
async function SM4DecryptBigData(secretData, secretKey) {
	//console.log('国科量子解密');
	let session=init()
	// //console.log('session',session);
	//console.log(secretData, secretKey);
	//secretData 是一个gk的URL
	//1 下载secretData
	let download =await download_data(secretData)
	//2 读取stream
	//读取文件流
	let stream=await resolveLocalFileSystemURL(download.tempFilePath)
	// //console.log(stream + "----------------->");
	
	//3 Stream->Str
	// let StreamString=JSON.stringify(stream)
	// //console.log(StreamString.length);
	////console.log('Stringeam',Stringeam);
	//4 SM4DecryptBigData 解密
	//console.log(session+'----------session-------------',stream.length+'---------stream.length----------',secretKey+'-------------secretKey-----------');
	
	let str = quantum.SM4DecryptBigData(session, stream, secretKey); //解密
	//console.log('解密结果',str.length, quantum.logError());
	let base64 ='data:image/jpg;base64,'+str.data
	// //console.log(base64.length);
	//5 base64解密
	//6 图片原始的stream
	return base64
}
//下载文件
function download_data(url) {
	return new Promise((reslove, reject) => {
		uni.downloadFile({
			url: url,
			success: (res) => {
				// //console.log(res);
				if (res.statusCode === 200) {
					// //console.log('下载成功');
					reslove(res)
				}else if(res.statusCode === 400){
					uni.showToast({
						title: '下载链接异常',
						icon:'none'
					});
				}
			},
			fail(error) {
				//console.log('下载失败',error);
				reject(error)
			}
		});
	})
}
//读取文件流
function resolveLocalFileSystemURL(tempFilePath) {
	return new Promise((reslove, reject) => {
		plus.io.resolveLocalFileSystemURL(tempFilePath, function(entry) {
			// 可通过entry对象操作文件 
			entry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsDataURL(file,'utf-8');
				fileReader.onloadend = function(evt) {
					//去除头部data:image/jpg;base64,留下base64编码后的字符串
					let index=evt.target.result.indexOf(',')
					let str=evt.target.result.slice(index + 1,evt.target.result.length)
					//base64解码
					let atob=quantum.Base64Decode(str);
					reslove(atob)
					// reslove(evt.target.result)
				}
				fileReader.onerror=function(error) {
					//console.log("读取文件失败" + JSON.stringify(error));
				}
				
				// //console.log(file.size + '--' + file.name);
			});
		}, function(e) {
			//console.log("Resolve file URL failed: " + e.message);
			reject(e.message)
		});
	})
}

/*
国科量子加密
需要传入加密的字符串
*/
function SM4EncryptBigData(secretData) {
	//console.log('国科量子加密');
	let session=init()
	// let session = uni.getStorageSync('GK_session')
	let res = quantum.SM4EncryptBigData(session, secretData) //加密
	//console.log('加密结果', res);
	return res
}
function initQSS(pub, pri, kek, zmk) {
	//加解密必须再走init()
	let session=init()
	//console.log('会话session', session);
	if(!session){
		uni.showToast({
			icon:"error",
			title:'国科初始化出错'
		})
		return
	}
	uni.setStorageSync('GK_session', session)
	//quantum.prepSymmKey(that.session);//加密解密之前必须调用一次此方法，生产密钥
	//console.log(pub);
	//console.log(pri);
	//console.log(kek);
	//console.log(zmk);
	let ret = quantum.setUsbKey(session, pub, pri, kek, zmk)

	if (ret != 0) {
		//console.log('出错了', ret);
		return
	}

}

let bInit = false;
let session = "";
function init(){
	if(!bInit) {
		let path=plus.io.convertLocalFileSystemURL('_www/static/cfg/skfapi.cfg');
		let ret = quantum.loadKey(path) //加载密钥
		if (ret != 0) {
			//console.log('出错了', quantum.logError());
			return
		}
		ret = quantum.open() //初始化“模拟的USB设备”环境
		if (ret != 0) {
			//console.log('出错了', quantum.logError());
			return
		}
		let devices = quantum.listDevices(); //获取设备名称
		if (devices == '') {
			//console.log('devices出错了', quantum.logError());
			return
		}
		quantum.connDevice(devices)
		session = quantum.getSession() //会话
		if (session == '') {
			//console.log('session出错了', quantum.logError());
			return
		}
		bInit = true;
	}
	return session
}

export default {
	qssList,
	SM4DecryptBigData,
	SM4EncryptBigData,
	initQSS,
	resolveLocalFileSystemURL,
	download_data
}
